import { ref, watch, onUnmounted } from "vue";
/**
 *
 * @param {number} number 变化到的数字
 * @param {object} options 配置对象
 * @param {number} options.duration 动画持续时间，单位毫秒，默认300
 * @param {number} options.delay 动画延迟时间，单位毫秒，默认0
 * @param {number} options.decimal 小数点位数，默认0
 */
export default function useTransition(number, options) {
  const { duration = 1500, delay = 0, decimal = 0 } = options || {};
  const animatedNumber = ref(0);
  let startTime = null;
  let animationId = null;
  const isNegative = number < 0; // 判断是否为负数
  const step = Math.abs(number - animatedNumber.value) / (duration / 16.66); // 计算每帧的步长
  if (delay) {
    setTimeout(() => {
      startAnimation();
    }, delay);
  } else {
    startAnimation();
  }

  function startAnimation() {
    startTime = Date.now();
    animationId = requestAnimationFrame(animate);
  }
  function animate() {
    const currentTime = Date.now();
    const diffTime = currentTime - startTime;
    if (animatedNumber.value >= number || diffTime >= duration) {
      animatedNumber.value = number; // 确保最终值正确
      cancelAnimationFrame(animationId);
      return;
    }
    if (diffTime < duration) {
      animatedNumber.value +=
        parseFloat(step.toFixed(decimal)) * (isNegative ? -1 : 1);
      animationId = requestAnimationFrame(animate);
    }
  }

  return animatedNumber;
}
